//
//  DbExchangeTable.m
//  MarketDataColloctor
//
//  Created by jiro on 10/03/10.
//  Copyright 2010 jiro music. All rights reserved.
//

#import "DbExchangeTableEntry_.h"
#import "DbUtility.h"
#import "../../Commons/Constants.h"
#import <vector>
#import <numeric>

@implementation DbExchangeTableEntry_

@synthesize	code;
@synthesize	exchangeDate;
@synthesize openPrice;
@synthesize closePrice;
@synthesize highPrice;
@synthesize lowPrice;

+ (DbExchangeTableEntry_*) dbExchangeTableEntryWithValues: (NSArray*) values
{
	DbExchangeTableEntry_* ret = [ [ DbExchangeTableEntry_ alloc ] init ];
	ret.code			= [ values objectAtIndex: 0 ];
	ret.exchangeDate	= [ NSDate dateWithString: [ DbUtility convertIsoStdDateStringToCocoaDateString: [ values objectAtIndex: 1 ] ] ];
	return ret;
}

+ (double) volatilityOf: (NSArray*) exchangeEntries forPriceFieldType: (PriceField::Type) type
{
	double adjust = 1000;
	double rateSum = 0.0;
	int count = [ exchangeEntries count ];
	for ( int i = 1; i < count; i++ )
	{
		DbExchangeTableEntry_* e1 = [ exchangeEntries objectAtIndex: i - 1 ];
		DbExchangeTableEntry_* e2 = [ exchangeEntries objectAtIndex: i ];
		double rate = [ e2 price: type ] / [ e1 price: type ];
		if ( rate > 1 )
		{
			rate -= 1.0;
		}
		else if ( rate < 1 )
		{
			rate = 1 - rate; 
		}
		rateSum += adjust * rate;
	}
	double volatility = rateSum / ( count - 1 );
	volatility /= adjust;
	return volatility;
}

- (NSString*) tableName
{
	NSException* exception =
	 [ [ NSException alloc ] 
		initWithName: kText_NotImplementedException 
		reason: kText_SelectorIsNotImplemented 
		userInfo: nil ];
	@throw exception;
}

- (double) price: (PriceField::Type) type
{
	switch ( type )
	{ 
	case PriceField::Type_StartPrice:
		return openPrice;
	case PriceField::Type_EndPrice:
		return closePrice;
	case PriceField::Type_HighestPrice:
		return highPrice;
	case PriceField::Type_LowestPrice:
		return lowPrice;
	case PriceField::Type_MiddleBetweenStartAndEnd:
		return ( openPrice + closePrice ) / 2.0;
	case  PriceField::Type_MiddleBetweenHighAndLow:
		return ( highPrice + lowPrice ) / 2.0;

	default: 
		@throw ( [ NSException  exceptionWithName: kText_ApplicationErrorException reason: @"" userInfo: nil ] );
	}
}

- (double) priceWidth
{
	return highPrice - lowPrice;
}

@end
